﻿<template>
  <div class="app-container">
    <div class="chart-title">档案管理</div>
    <div class="chart-content">
      <div class="filter-title">
        <el-form
          label-position="right"
          @submit.native.prevent
        >
          <el-form-item>
            <el-input
              v-model="listQuery.name"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('operations.searchName')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="listQuery.region_name"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('region.districtName')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="listQuery.linkman"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('public.linkman')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
          <div
            class="search-button"
            @click="handleFilter"
          >
            <img src="@/assets/images/bg_search@2x.png" />
          </div>
          <div
            class="search-button"
            @click="handleRefresh"
          >
            <img src="@/assets/images/bg_reset@2x.png" />
          </div>
          <div
            class="search-button"
            @click="searchItem"
          >
            <img
              v-show="showSearchItem === true"
              src="@/assets/images/bg_more@2x.png"
            />
            <img
              v-show="showSearchItem === false"
              src="@/assets/images/bg_sx@2x.png"
            />
          </div>
        </el-form>
        <div class="filter-right">
          <div
            class="add-button"
            @click="handleCreate"
          >
            <img src="@/assets/images/icon_add@2x.png" />
            <span>新建</span>
          </div>
        </div>
      </div>
      <div
        v-show="showSearchItem"
        class="filter-container"
      >
        <el-form @submit.native.prevent>
          <el-form-item>
            <el-input
              v-model="listQuery.linkman_mobile"
              style="width: 160px; height:32px;"
              class="filter-item"
              :placeholder="$t('public.mobile')"
              @keyup.enter.native="handleFilter"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="chart-list">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255,255,255,0.2)"
          border
          fit
          highlight-current-row
          style="width: 100%min-height:1000px"
        >
          <el-table-column
            fixed="left"
            align="center"
            :label="$t('table.id')"
            width="65"
          >
            <template slot-scope="scope">
              <span>{{
                (listQuery.page - 1) * listQuery.limit + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('operations.name')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('region.districtName')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.region_name }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.linkman')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.linkman }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('public.mobile')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.linkman_mobile }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            show-overflow-tooltip
            :label="$t('equipment.count')"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.equipment_count }}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            :label="$t('table.actions')"
            class-name="operat-button"
            fixed="right"
          >
            <template slot-scope="scope">
              <div
                class="read-img"
                @click="handleRead(scope.row)"
              >
                <img src="@/assets/images/read@2x.png" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
      <!-- 编辑 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="35%"
          style="width: 400px margin-left:120px"
          size="small"
        >
          <div class="pops">
            <div class="information-title">
              <span class="icon-title"></span>
              <span>基础信息:</span>
            </div>
            <div class="pops-item">
              <div class="pops-left">
                <el-form-item
                  :label="$t('operations.name') + ' :'"
                  prop="name"
                >
                  <el-input
                    v-model="temp.name"
                    :readonly="dialogStatus !== 'create' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('operations.region') + ' :'"
                  prop="admin_region_id"
                >
                  <el-select
                    v-model="temp.admin_region_id"
                    clearable
                    style="width: 150px"
                    class="filter-item"
                    :placeholder="$t('public.default')"
                    :disabled="dialogStatus !== 'create' ? true : false"
                    @change="getArea(1,'','getArea')"
                  >
                    <el-option
                      v-for="item in districtsOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  :label="$t('region.name') + ' :'"
                  prop="region_id"
                >
                  <drop-down-select
                    optionName="region_name"
                    :data="areaOptions"
                    :count="areaCount"
                    :page-size="pageSize"
                    :disabled="dialogStatus !== 'create' ? true : false"
                    :id="temp.region_id"
                    :name="temp.region_name"
                    @getList="(pageNumber, search)=>{return getArea(pageNumber, search,'getArea')}"
                    @addList="(pageNumber, search)=>{return getArea(pageNumber, search,'addArea')}"
                    @choose="(data)=>{return choose(data, 'area')}"
                    @remove="(data)=>{return remove(data, 'area')}"
                  ></drop-down-select>
                </el-form-item>
              </div>
              <div class="pops-right">
                <el-form-item
                  :label="$t('public.linkman') + ' :'"
                  prop="linkman"
                >
                  <el-input
                    v-model="temp.linkman"
                    :readonly="dialogStatus !== 'create' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('public.mobile') + ' :'"
                  prop="linkman_mobile"
                >
                  <el-input
                    v-model="temp.linkman_mobile"
                    :readonly="dialogStatus !== 'create' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('operations.deadline') + ' :'"
                  prop="deadline"
                >
                  <el-select
                    v-model="temp.deadline"
                    clearable
                    style="width: 150px"
                    class="filter-item"
                    :placeholder="$t('operations.deadline')"
                    :disabled="dialogStatus !== 'create' ? true : false"
                    prop="deadline"
                  >
                    <el-option
                      v-for="item in deadlineOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <div class="information-title">
              <span class="icon-title"></span>
              <span>支付信息:</span>
            </div>
            <div class="pops-item">
              <div class="pops-left">
                <el-form-item
                  :label="$t('operations.bankAccountName') + ' :'"
                  prop="bank_account_name"
                >
                  <el-input
                    v-model="temp.bank_account_name"
                    :readonly="dialogStatus == 'read' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('operations.bankAccountNumber') + ' :'"
                  prop="bank_account_number"
                >
                  <el-input
                    v-model="temp.bank_account_number"
                    :readonly="dialogStatus == 'read' ? true : false"
                  ></el-input>
                </el-form-item>
              </div>
              <div class="pops-right">
                <el-form-item
                  :label="$t('operations.bankName') + ' :'"
                  prop="bank_name"
                >
                  <el-input
                    v-model="temp.bank_name"
                    :readonly="dialogStatus == 'read' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item
                  :label="$t('operations.bankAddress') + ' :'"
                  prop="bank_address"
                >
                  <el-input
                    v-model="temp.bank_address"
                    :readonly="dialogStatus == 'read' ? true : false"
                  ></el-input>
                </el-form-item>
              </div>
            </div>
          </div>
        </el-form>
        <div
          slot="footer"
          class="dialog-footer between-space"
        >
          <div>
            <el-button
              v-show="dialogStatus == 'read'"
              type="primary"
              @click="handleEdit"
            >{{ $t("table.edit") }}</el-button>
          </div>
          <div>
            <el-button @click="dialogFormVisible = false">{{
              $t("table.cancel")
            }}</el-button>
            <el-button
              v-if="dialogStatus == 'create'"
              type="primary"
              :disabled="!createDisabled"
              @click="createData"
            >{{ $t("table.confirm") }}</el-button>
            <el-button
              v-else-if="dialogStatus == 'edit'"
              type="primary"
              :disabled="!updateDisabled"
              @click="updateData"
            >{{ $t("table.confirm") }}</el-button>
            <el-button
              v-else
              type="primary"
              @click="dialogFormVisible = false"
            >{{ $t("table.confirm") }}</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script type="text/javascript">
import { getToken } from "@/utils/auth"; // get token from cookie
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
export default {
  name: "Itoc",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    const validateName = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error("名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号")
            );
          }
        }
      } else {
        callback(new Error("请填写名称"));
      }
    };
    const validateLinkman = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 16) {
          callback(new Error("名称长度不能大于16个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)(?!(\、+)$)[\u4e00-\u9fff\w\、]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error(
                "联系人只能包含汉字、英文、“_”、“（”、“）”和数字且不为纯数字或纯符号"
              )
            );
          }
        }
      } else {
        callback(new Error("请填写联系人"));
      }
    };
    const validateLinkmanMobile = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        var reg = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/; /* 定义验证表达式 */
        if (reg.test(value)) {
          /* 进行验证 */
          callback();
        } else {
          callback(new Error("请输入正确的联系电话"));
        }
      } else {
        callback(new Error("请填写联系电话"));
      }
    };
    const bankAccountName = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 16) {
          callback(new Error("长度不能大于16个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)(?!(\、+)$)[\u4e00-\u9fff\w\、]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error(
                "银行开户名只能包含汉字、英文、“_”、“（”、“）”和数字且不为纯数字或纯符号！"
              )
            );
          }
        }
      } else {
        callback(new Error("请填写银行开户名！"));
      }
    };
    const bankAccountNumber = (rule, value, callback) => {
      if (value.length > 0) {
        var reg = /^([1-9]{1})(\d{14}|\d{18})$/; /* 银行卡号验证 */
        if (reg.test(value)) {
          /* 进行验证 */
          callback();
        } else {
          callback(new Error("请输入正确的银行账号！"));
        }
      } else {
        callback(new Error("请填写银行账号！"));
      }
    };
    const charge_ratio = (rule, value, callback) => {
      if (value || value === 0) {
        if (value > 0 && value < 100) {
          callback();
        } else {
          callback(new Error("收费比例大于0小于100！"));
        }
      } else {
        callback();
      }
    };
    return {
      showSearchItem: false,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      deadlineOptions: [
        {
          value: 1,
          label: "1年"
        },
        {
          value: 2,
          label: "2年"
        },
        {
          value: 3,
          label: "3年"
        },
        {
          value: 99,
          label: "不限"
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        code: "",
        status: "",
        linkname: "",
        linkname_mobile: "",
        region_name: "",
        region_type: ""
      },
      districtsOptions: [],
      temp: {
        id: undefined,
        name: "",
        admin_region_id: undefined,
        admin_region_name: "",
        linkman: "",
        linkman_mobile: "",
        region_id: undefined,
        region_name: "",
        bank_account_name: "",
        bank_account_number: "",
        bank_name: "",
        bank_address: "",
        deadline: ""
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "编辑",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        name: [{ required: true, trigger: "blur", validator: validateName }],
        linkman: [
          { required: true, trigger: "blur", validator: validateLinkman }
        ],
        linkman_mobile: [{ required: true, trigger: "blur", validator: validateLinkmanMobile }],
        admin_region_id: [
          { required: true, message: "请选择所属区", trigger: "change" }
        ],
        region_id: [{ required: true, message: "请选择区域", trigger: "change" }],
        deadline: [
          { required: true, message: "请选择有效期", trigger: "change" }
        ],
        bank_account_name: [
          { required: true, trigger: "blur", validator: bankAccountName }
        ],
        bank_account_number: [
          { required: true, trigger: "blur", validator: bankAccountNumber }
        ],
        bank_name: [
          {
            required: true,
            message: "请输入开户银行支行名称",
            trigger: "blur"
          }
        ],
        bank_address: [
          { required: true, message: "开户银行所在地", trigger: "blur" }
        ],
        charge_ratio: [
          { required: true, trigger: "blur", validator: charge_ratio }
        ]
      },
      createDisabled: true,
      updateDisabled: true,
      areaOptions: [],
      areaCount: undefined,
      pageSize: 20
    };
  },
  created() {
    const token = getToken()
    if (token && !this.$store.state.socket.loginTransition && !this.$store.state.socket.loginAccount) {
      this.tokenLogin(token)
    }
    this.getList();
  },
  mounted() {
    this.getDistricts();
  },
  methods: {
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        name: "",
        code: "",
        status: "",
        linkname: "",
        linkname_mobile: "",
        region_name: "",
        region_type: ""
      };
      this.getList();
    },
    searchItem() {
      if (this.showSearchItem === true) {
        this.showSearchItem = false;
      } else {
        this.showSearchItem = true;
      }
    },
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page,
        region_name: this.listQuery.region_name ? this.listQuery.region_name : "",
        name: this.listQuery.name ? this.listQuery.name : "",
        linkman: this.listQuery.linkman ? this.listQuery.linkman : "",
        linkman_mobile: this.listQuery.linkman_mobile ? this.listQuery.linkman_mobile : ""
      };
      const path = {
        // 获取营运中心列表
        app: "archives",
        api: "api_archives_itoc_itocList",
        version: "1.0",
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleRead(row) {
      // 打开查看弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "read";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleEdit() {
      this.dialogStatus = "edit";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 更新数据
    upData() {
      let admin_region_name = "";
      this.districtsOptions.forEach(element => {
        if (this.temp.admin_region_id === element.id) {
          admin_region_name = element.name;
        }
      });
      const data = {
        id: this.temp.id ? this.temp.id : "",
        name: this.temp.name ? this.temp.name : "",
        admin_region_id: this.temp.admin_region_id
          ? this.temp.admin_region_id
          : "",
        admin_region_name: admin_region_name,
        linkman: this.temp.linkman ? this.temp.linkman : "",
        linkman_mobile: this.temp.linkman_mobile
          ? this.temp.linkman_mobile
          : "",
        region_id: this.temp.region_id ? this.temp.region_id : "",
        region_name: this.temp.region_name ? this.temp.region_name : "",
        bank_account_name: this.temp.bank_account_name
          ? this.temp.bank_account_name
          : "",
        bank_account_number: this.temp.bank_account_number
          ? this.temp.bank_account_number
          : "",
        bank_name: this.temp.bank_name ? this.temp.bank_name : "",
        bank_address: this.temp.bank_address ? this.temp.bank_address : "",
        deadline: this.temp.deadline ? this.temp.deadline : ""
      };
      return data;
    },
    createData() {
      // 添加运营中心档案
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.createDisabled) {
            this.createDisabled = false;
            const data = this.upData();
            const path = {
              app: "archives",
              api: "api_archives_itoc_add",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.createDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    updateData() {
      // 更新运营中心档案
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            const data = this.upData();
            const path = {
              app: "archives",
              api: "api_archives_itoc_edit",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        admin_region_id: undefined,
        admin_region_name: "",
        linkman: "",
        linkman_mobile: "",
        region_id: undefined,
        region_name: "",
        bank_account_name: "",
        bank_account_number: "",
        bank_name: "",
        bank_address: "",
        deadline: ""
      };
    },
    // 获取七大区列表
    getDistricts() {
      const path = {
        app: "archives",
        api: "api_archives_itoc_sevenRegional",
        version: "1.0",
        data: {}
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 区域选择
    getArea(pageNumber, search, name) {
      if (this.temp.admin_region_id) {
        const path = {
          app: "common",
          api: "api_common_index_getCityList",
          version: "1.0",
          data: {
            admin_region_id: this.temp.admin_region_id,
            rows: this.pageSize,
            page: pageNumber || 1,
            region_name: search || "",
            returnType: name || ""
          }
        };
        this.socketApi.sendSock(JSON.stringify(path), res => {
          if (res) {
            this.socketData(res);
          }
        });
      } else {
        this.temp.region_id = undefined;
        this.temp.region_name = "";
        this.areaOptions = [];
      }
    },
    choose(data, name) {
      if (name === 'area') {
        this.temp.region_id = data.id;
        this.temp.region_name = data.region_name;
      }
    },
    remove(data, name) {
      if (name === 'area') {
        this.temp.region_id = undefined;
        this.temp.region_name = "";
      }
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            })
          } else if (resj.api === "api_archives_itoc_itocList") {
            this.total = resj.count;
            this.list = resj.data;
            this.listLoading = false;
          } else if (resj.api === "api_archives_itoc_sevenRegional") {
            this.districtsOptions = resj.data;
          } else if (
            resj.api === "api_common_index_getCityList" &&
            resj.type === "getArea"
          ) {
            this.areaOptions = resj.data;
            this.areaCount = resj.count;
          } else if (
            resj.api === "api_common_index_getCityList" &&
            resj.type === "addArea"
          ) {
            this.areaOptions = this.areaOptions.concat(resj.data);
          } else if (resj.api === "api_archives_itoc_add") {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_archives_itoc_edit") {
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          }
        }
      }
    }
  }
};
</script>
